package com.pig4cloud.pigx.common.security.service;
import com.pig4cloud.pigx.admin.api.entity.ToCUser;
import com.pig4cloud.pigx.admin.api.feign.DuckweedRemoteUserService;
import com.pig4cloud.pigx.common.core.constant.SecurityConstants;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;


/**
 * @date:2022/8/11
 */
@RequiredArgsConstructor
public class RooTocUserDetailsServiceImpl implements PigxUserDetailsService {

	private final DuckweedRemoteUserService remoteUserService;

	// 登录流程获取token使用
	@Override
	@SneakyThrows
	public UserDetails loadUserByUsername(String username) {
		ToCUser user = remoteUserService.userInfo(username, SecurityConstants.FROM_IN).getData();
		if (user == null) {
			return new PigxUser(
					500L,
					username,
					null,
					"Phone",
					"Avatar",
					"500",
					"500",
					"",
					1L,
					"{noop}" + username,
					true,
					true,
					true,
					true,
					AuthorityUtils.NO_AUTHORITIES
			);
		}
		Boolean enabled = true;
		//判断用户是否禁用
		//用户名和密码为数据库中存储的授权钱包地址
		return new PigxUser(user.getId(), user.getAddress(), null,
				"Phone", "Avatar", user.getId().toString(),
				user.getId().toString(), user.getEmail(), 1L,
				"{noop}" + user.getAddress(), enabled, true,
				true, true, AuthorityUtils.NO_AUTHORITIES);
	}

	// check-token 校验token使用
	@Override
	public UserDetails loadUserByUser(PigxUser pigxUser) {
		// 根据 pigxUser 里面的信息 查询对应表 返回 UserDetails，pigxUser.getUsername()为数据库存储的 授权钱包地址
		return this.loadUserByUsername(pigxUser.getUsername());
	}


	@Override
	public boolean support(String clientId, String grantType) {
		return "dapp".equals(clientId);
	}

	/**
	 * 排序值
	 *
	 * @return 排序值
	 */
	@Override
	public int getOrder() {
		return 10;
	}

}


